package com.zw.mes.module.prodtaskmanager.controller;

import com.zw.mes.base.BaseController;
import com.zw.mes.common.JsonResult;
import com.zw.mes.module.assemble.entity.AsseStore;
import com.zw.mes.module.overview.model.ProductModel;
import com.zw.mes.module.prodtaskmanager.entity.VwPreEnquiryFile;
import com.zw.mes.module.prodtaskmanager.mapper.ProdOrdMapper;
import com.zw.mes.module.prodtaskmanager.model.PreEnquiry;
import com.zw.mes.module.prodtaskmanager.model.ProChange;
import com.zw.mes.module.prodtaskmanager.model.ProjectModel;
import com.zw.mes.module.prodtaskmanager.model.ProjectSchedulingModel;
import com.zw.mes.module.prodtaskmanager.service.ProjectChangeQueryService;
import com.zw.mes.module.system.service.LogService;
import com.zw.mes.util.FTPUtil;
import com.zw.mes.util.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 项目变更记录查询
 *
 * @author XYH
 */
@Controller
public class ProjectChangeQueryController extends BaseController {

    @Autowired
    private ProjectChangeQueryService projectChangeQueryService;

    @Autowired
    private LogService logService;
    @Autowired
    private ProdOrdMapper prodOrdMapper;

    @GetMapping("/overview/projectChangeQuery")
    @RequiresPermissions("overview:projectChangeQuery:view")
    public String page() {
        return "/overview/projectChangeQuery/page";
    }

    /**
     * 生产进度查询页面跳转
     *
     * @return
     */
    @GetMapping("/overview/productQuery")
    public String pageProduct(Model model) {
        ProductModel productModel = new ProductModel();
        productModel.setType(0);
        double solderAllNum = prodOrdMapper.selectSolderAllNum(productModel);
        double solderCompleteNum = prodOrdMapper.selectSolderCompleteNum(productModel);
        double sprayAllNum = prodOrdMapper.selectSprayAllNum(productModel);
        double sprayCompleteNum = prodOrdMapper.selectSprayCompleteNum(productModel);
        int machiningAllNum = prodOrdMapper.selectMachiningAllNum(productModel);
        int machiningCompleteNum = prodOrdMapper.selectMachiningCompleteNum(productModel);
        model.addAttribute("solderSurplusNum", String.format("%.2f", (solderAllNum - solderCompleteNum)));
        model.addAttribute("spraySurplusNum", String.format("%.2f", (sprayAllNum - sprayCompleteNum)));
        model.addAttribute("machiningSurplusNum", getNum(machiningAllNum - machiningCompleteNum));
        Calendar cal = Calendar.getInstance(); //取得当前日历
        int year = cal.get(Calendar.YEAR);
        List<ProductModel> list = new ArrayList<>();
        for (int i = year; i >2020; i--) {
                ProductModel productModel1 = new ProductModel();
                productModel1.setYear("" + i);
                list.add(productModel1);
        }
        model.addAttribute("year", list);
        return "/overview/productQuery/page";
    }

    /**
     * 生产进度查询明细页面跳转
     *
     * @param time
     * @param model
     * @return
     */
    @GetMapping("/product/detail/viewInfo/{time}")
    public String productInfoPage(@PathVariable("time") String time, Model model) {

        model.addAttribute("yearMonth", time);
        int month = Integer.parseInt(time.substring(time.indexOf("-") + 1));
        model.addAttribute("yearMonthDayStart", getFirstDayOfMonth(month));
        model.addAttribute("yearMonthDayEnd", getLastDayOfMonth(month));
        return "overview/productQuery/info";
    }

    /**
     * 获取当前月第一天
     *
     * @param month
     * @return
     */
    public String getFirstDayOfMonth(int month) {
        Calendar calendar = Calendar.getInstance();
        // 设置月份
        calendar.set(Calendar.MONTH, month - 1);
        // 获取某月最小天数
        int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
        // 设置日历中月份的最小天数
        calendar.set(Calendar.DAY_OF_MONTH, firstDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(calendar.getTime()) + " 00:00:00";
    }

    public String getLastDayOfMonth(int month) {
        Calendar calendar = Calendar.getInstance();
        // 设置月份
        calendar.set(Calendar.MONTH, month - 1);
        // 获取某月最大天数
        int lastDay = 0;
        //2月的平年瑞年天数
        if (month == 2) {
            lastDay = calendar.getLeastMaximum(Calendar.DAY_OF_MONTH);
        } else {
            lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        // 设置日历中月份的最大天数
        calendar.set(Calendar.DAY_OF_MONTH, lastDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(calendar.getTime()) + " 23:59:59";
    }

    /**
     * 加载日期格中数据
     *
     * @param time
     * @return
     */
    @ResponseBody
    @PostMapping("/product/detail/infoDetail")
    public JsonResult infoDetail(String time) {

        return jsonResult(projectChangeQueryService.getProductModelList(time));
    }

    public String getNum(int num) {
        return num / 60 + "." + (num % 60 >= 10 ? num % 60 : "0" + num % 60);
    }

    /**
     * 生产进度查询列表加载
     *
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/projectScheduling/selectProductList")
    public JsonResult selectProductList(ProductModel model) {
//        startPage();


        return jsonResult(projectChangeQueryService.selectProductList(model));
    }

    /**
     * 生产进度查询明细模态框列表加载
     */
    @ResponseBody
    @PostMapping("/projectScheduling/productDetailList")
    public JsonResult productDetailList(ProductModel productModel) {

        return jsonResult(projectChangeQueryService.selectCL(productModel));
    }

    /**
     * 查询项目变更
     *
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/projectScheduling/selectProjectChangeList")
    @RequiresPermissions("overview:projectChangeQuery:view")
    public JsonResult selectProjectChangeList(ProjectSchedulingModel model) {
        startPage();
        return jsonResult(projectChangeQueryService.selectProjectChangeList(model));
    }

    /**
     * 变更通知查看页面
     *
     * @param proChangeId
     * @param model
     * @return
     */
    @GetMapping("/projectChange/chgInfo/viewInfo/{proChangeId}")
    @RequiresPermissions("overview:projectChangeQuery:view")
    public String viewInfoPage(@PathVariable("proChangeId") Integer proChangeId, Model model) {
        ProjectModel projectChgInfo = projectChangeQueryService.selectChangeInfoById(proChangeId);
        model.addAttribute("projectChgInfo", projectChgInfo);
        model.addAttribute("proChangeId", proChangeId);
        ProChange proChange = projectChangeQueryService.selectByPrimaryKey(proChangeId);
        if (proChange.getPreEnqId() != null) {
            PreEnquiry preEnquiry = projectChangeQueryService.selectPreEnqById(proChange.getPreEnqId());
            model.addAttribute("preFiles", projectChangeQueryService.findChangeFileListByEnquiryId(preEnquiry.getId(), preEnquiry.getOrigId()));
        }
        return "overview/projectChangeQuery/info/page";
    }

    /**
     * @methodName: downloadFile
     * @description: 变更查询下载
     * @param: id
     * @param: httpServletResponse
     * @return： void
     * @exception：
     * @author： 徐一贺 tel:18341916590
     * @designer： 陈欣，盖世奇
     * @leader： 陈欣 tel:18104194240
     * @date： 2021/4/7 9:58
     * @office: 智能控制设计科
     * @research institute： 智能控制设计所
     * @department： 机械设计院
     * @company: 辽宁忠旺机械设备制造有限公司
     * @group： 忠旺集团
     * @version: 1.0
     */
    @GetMapping("proChangeQuery/downloadFile/{id}")
    @RequiresPermissions("overview:projectChangeQuery:download")
    public void downloadFile(@PathVariable("id") Integer id, HttpServletResponse httpServletResponse) {
        VwPreEnquiryFile vwPreEnquiryFile = projectChangeQueryService.getVwPreEnquiryFileByPrimary(id);
        String filename = vwPreEnquiryFile.getUrl();
        filename = "e:\\sale\\upload\\" + filename.substring(7).replace("/", "\\");
        FileUtils.downloadFile(filename, httpServletResponse);
        logService.saveLog(
                "项目变更查询-->变更通知单-->下载附件",
                "");
    }
}
